package model

import (
	"community_end/utils/errmsg"
	"gorm.io/gorm"
	"strconv"
)

type Post struct {
	gorm.Model
	Title     string `json:"title"`
	Content   string `json:"content"`
	UserID    int
	Collects  int
	View      int `json:"view"`
	Top       int
	Essence   int
	SectionID int
	Tags      []Tag     `json:"tags" gorm:"many2many:post_tag;"`
	Comments  []Comment `gorm:"foreignKey:PostID"`
}

func (Post) TableName() string {
	return "post"
}

func SelectAllPost() ([]Post, int) {
	var posts []Post
	db.Find(&posts)
	return posts, len(posts)
}

func SelectPostList(page, pageSize int) ([]Post, int) {
	var posts []Post
	err := db.Preload("Tags").Offset((page - 1) * pageSize).Limit(pageSize).Find(&posts).Error
	if err != nil {
		return nil, errmsg.POST_SELECT_FAILED
	}
	return posts, errmsg.SUCCESS
}

func InsertPost(p Post) (int, int) {
	err := db.Create(&p).Error
	if err != nil {
		return 0, errmsg.POST_CREATE_FAILED
	}
	return int(p.ID), errmsg.SUCCESS
}

func SelectPostByID(id string) (*Post, int) {
	convID, _ := strconv.Atoi(id)
	post := &Post{}
	err := db.Preload("Tags").Where("id = ?", convID).First(post).Error
	if err != nil {
		return nil, errmsg.POST_SELECT_FAILED
	}
	return post, errmsg.SUCCESS
}

func GetRecommendTopic() ([]*Post, int) {
	posts := []*Post{}
	err := db.Order("id").Limit(10).Find(&posts).Error
	if err != nil {
		return nil, errmsg.POST_SELECT_FAILED
	}
	return posts, errmsg.SUCCESS
}

func SavePost(post Post) int {
	err := db.Save(&post).Error
	if err != nil {
		return errmsg.POST_CREATE_FAILED
	}
	return errmsg.SUCCESS
}

func DeleteTopic(id string) int {
	err := db.Where("id = ?", id).Delete(&Post{}).Error
	if err != nil {
		return errmsg.POST_DELETE_FAILED
	}
	return errmsg.SUCCESS
}

func SelectLikeKeyword(keyword string) ([]Post, int) {
	posts := []Post{}
	err := db.Debug().Where("title like ?", "%"+keyword+"%").Find(&posts).Error
	if err != nil {
		return nil, errmsg.POST_SELECT_FAILED
	}
	return posts, errmsg.SUCCESS
}
